# 前端组件化
# 一、模板引擎
适用场景
- 多页面应用(MPA)开发
- 需服务端动态渲染的页面
- 渐进式升级的老项目
模板引擎
Pug (opens new window) | Jade (opens new window) | EJS (opens new window) | Handlebars (opens new window) | Mustache (opens new window)
构建工具
# 目录结构
src/
├── layouts/
│ └── main.pug # 主布局模板
├── partials/ # 公共组件
│ ├── header.pug
│ ├── sidebar.pug
│ └── footer.pug
└── pages/
└── dashboard.pug # 业务页面
# 代码示例
//- 主布局模板(layouts/main.pug)
doctype html
html
head
title= title
include ../partials/header
body
include ../partials/sidebar
block content
include ../partials/footer
//- 业务页面(pages/dashboard.pug)
extends ../layouts/main.pug
block content
h1 控制面板
//- 页面专属内容
# 二、静态网站生成器
编译时生成静态 HTML(SSG (opens new window))
天然支持 Markdown 内容
与 Git 工作流深度集成
主流工具
Jekyll (opens new window) | Hugo (opens new window) | Eleventy (opens new window) | Wintersmith (opens new window) | Harp (opens new window)
Jekyll 实现示例:
<!-- 布局模板(_layouts/default.html) -->
<html>
{% include header.html %}
<body>{{ content }}</body>
</html>
<!-- 组件(_includes/header.html) -->
<nav class="main-header">
{{ site.title }} <!-- 动态配置注入 -->
</nav>
# 三、前端框架组件化
# SPA 开发模式
<!-- Vue3 + AdminLTE示例 -->
<template>
<AdminLayout>
<Sidebar :menuItems="menu"/>
<Header :user="currentUser"/>
<router-view/> <!-- 动态内容区 -->
</AdminLayout>
</template>
# SSR 框架整合
Next.js (opens new window) | Nuxt.js (opens new window)
同时支持组件化与服务端渲染,替代传统模板方案。
# 四、服务端模板
# PHP 方案
<?php
// 引入公共头部
include('partials/header.php');
?>
<div class="content">
<?php if($isAdmin): ?>
<admin-panel/>
<?php endif; ?>
</div>
<?php include('partials/footer.php'); ?>
# Node.js 方案
Express + EJS:
// app.js 配置视图引擎
app.set('view engine', 'ejs');
// routes.js 路由渲染
router.get('/', (req, res) => {
res.render('dashboard', { title: '控制台' });
});
# 五、HTML 引入
# 浏览器原生方案
<object
type="text/html"
data="sidebar.html"
style="width:100%">
</object>
# 服务端包含
服务器端包含(Server Side Include,SSI):
<!-- 需配置Nginx/Apache支持 -->
<!-- #include virtual="/partials/header.html" -->